package {
	import effects.FlashEffect;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Endian;
	import flash.utils.getTimer;
		
	import flash.ui.Mouse;
	import part.TestPart;
	import evo.engine.AbstractDemo;
	
	[Frame(factoryClass="evo.engine.DefaultPreloader")]
	
	[SWF(width="800", height="400", frameRate="31", backgroundColor="#000000")]
	public class DemoMain extends AbstractDemo
	{	
		private var started:Boolean = false;
		private var demoSync:DemoSynch;
		
		public function DemoMain()
		{
			// Load song and initialize beat sync
			demoSync = new DemoSynch();
			super("song.mp3", demoSync, true);
		}
		
	    override protected function songLoaded(evt:Event):void
		{
			super.songLoaded(evt);
			demoSync.flash.addListener(onFlash);
			demoSync.longflash.addListener(onLongFlash);
		}

		private var flashEffect:FlashEffect;
		
		public function onFlash(dt:int):void
		{
			if(flashEffect.done)
			{
				engine.addEffect(flashEffect);
				engine.addEventListener(Event.ENTER_FRAME, onFlashFrame);
			}						
			flashEffect.speed=1;
			flashEffect.reset();
		}

		public function onLongFlash(dt:int):void
		{
			if(flashEffect.done)
			{
				engine.addEffect(flashEffect);
				engine.addEventListener(Event.ENTER_FRAME, onFlashFrame);
			}						
			flashEffect.speed=4;
			flashEffect.reset();
		}
		
		private function onFlashFrame(evt:Event):void
		{
			if(flashEffect == null)
			{
				engine.removeEventListener(Event.ENTER_FRAME, onFlashFrame);
			}
			
			if(flashEffect.done)
			{
				trace("Removink");
				engine.removeEffect(flashEffect);
				engine.removeEventListener(Event.ENTER_FRAME, onFlashFrame);
			}
		}		
		
		protected override function generateParts():void
		{
			super.generateParts();
			flashEffect = new FlashEffect();
			flashEffect.init(engine.buffer);
			
			engine.addPart(new TestPart(demoSync));

			// We handle the screenflashing simply here, becasue flash effect is "global"
			demoSync.flash.addListener(onFlash);
			demoSync.longflash.addListener(onLongFlash);
			
		}
	}
}
